/*
 * BSM6.0
 *
 * Copyright 2012-2013 (C) SINODATA CO., LTD. All Rights Reserved.
 */
package com.sinodata.bsm.center.dao.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.hibernate.Query;
import org.springframework.stereotype.Repository;

import com.sinodata.bsm.center.bean.Condition;
import com.sinodata.bsm.center.bean.Page;
import com.sinodata.bsm.center.dao.BaseDao;
import com.sinodata.bsm.center.dao.TrapDao;
import com.sinodata.bsm.common.vo.FaultTrapMsg;

/**
 * <p>
 * Description: 
 * </p>
 *
 * @author wangyazhou
 * @version 1.0

 * <p>
 * History: 
 *
 * Date                     Author         Version     Description
 * ---------------------------------------------------------------------------------
 * 2012-12-10 上午11:29:43          wangyazhou        1.0         To create
 * </p>
 *
 * @since 
 * @see     
 */

@Repository
public class TrapDaoImpl extends BaseDao implements TrapDao {

    private static final Logger logger = Logger.getLogger(TrapDaoImpl.class);

    @SuppressWarnings("unchecked")
    @Override
    public Page<FaultTrapMsg> findByPage(Page<FaultTrapMsg> page, Condition condition) {
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        StringBuilder sb = new StringBuilder("select t.id,");
        sb.append(" t.source_ip,");
        sb.append(" to_char(t.recev_time,'yyyy-MM-dd hh24:mi:ss'),");
        sb.append(" t.security_level,");
        sb.append(" t.security_name,");
        sb.append(" t.request_id,");
        sb.append(" t.error_status,");
        sb.append(" t.error_index,");
        sb.append(" t.generic_trap,");
        sb.append(" t.specific_trap,");
        sb.append(" t.time_stamp,");
        sb.append(" t.ext_msg,");
        sb.append(" t.msg,");
        //        sb.append(" t.msg_1,");
        sb.append(" t.msg_2,");
        sb.append(" t.msg_3,");
        sb.append(" t.snmp_version");
        sb.append(" from fault_trap_msg t");
        sb.append(" where 1=1 ");
        sb.append(getConditonSql(condition));
        sb.append(" order by t.recev_time desc");

        //        logger.info(sb.toString());

        page.setTotal(getTotal(condition));
        Query query = getSession().createSQLQuery(sb.toString()).setFirstResult(page.getFirstResultNo()).setMaxResults(page.getPageSize());
        List<Object[]> list = query.list();
        List<FaultTrapMsg> trapList = new ArrayList<FaultTrapMsg>();
        for (Object[] obj : list) {
            FaultTrapMsg trap = new FaultTrapMsg();
            trap.setId(Long.parseLong(String.valueOf(obj[0])));
            trap.setIp(String.valueOf(obj[1]));
            try {
                trap.setRecevTime(sf.parse(String.valueOf(obj[2])));
            } catch (Exception e) {
            }
            trap.setSecLevel(Integer.parseInt(String.valueOf(obj[3])));
            trap.setSecName(String.valueOf(obj[4]));
            trap.setRequestId(Long.parseLong(String.valueOf(obj[5])));
            trap.setErrorStatus(String.valueOf(obj[6]));
            trap.setErrorIndex(String.valueOf(obj[7]));
            trap.setGenericTrap(String.valueOf(obj[8]));
            trap.setSpecificTrap(String.valueOf(obj[9]));
            trap.setTimeStamp(String.valueOf(obj[10]));
            trap.setExtMsg(String.valueOf(obj[11]));

            //            trap.setMsg1(String.valueOf(obj[12]));
            trap.setMsg(String.valueOf(obj[12]));
            trap.setMsg2(String.valueOf(obj[13]));
            trap.setMsg3(String.valueOf(obj[14]));
            trap.setVersion(String.valueOf(obj[15]));
            trapList.add(trap);
        }

        page.setRows(trapList);
        return page;
    }

    /**
     * 获取总数
     * 
     * @param condition
     * @return
     */
    private int getTotal(Condition condition) {
        StringBuilder sb = new StringBuilder(" select count(1) ");
        sb.append(" from fault_trap_msg t");
        sb.append(" where 1 = 1 ");
        sb.append(getConditonSql(condition));

        //        logger.info(sb.toString());
        Query query = this.getSession().createSQLQuery(sb.toString());
        return ((java.math.BigDecimal) query.list().iterator().next()).intValue();
    }

    /**
     * 构造查询条件
     * @param condition
     * @return
     */
    private StringBuilder getConditonSql(Condition condition) {
        StringBuilder sb = new StringBuilder();
        Map<String, String> condMap = condition.getWhere();
        String ip = condMap.get("ip");
        if (ip != null && ip.length() > 0) {
            sb.append(" and t.source_ip like '%" + ip + "%'");
        }
        String start = condMap.get("start");
        if (start != null && start.length() > 0) {
            sb.append(" and t.recev_time >=to_date('" + start + "','yyyy-MM-dd hh24:mi:ss')");
        }
        String end = condMap.get("end");
        if (end != null && end.length() > 0) {
            sb.append(" and t.recev_time <= to_date('" + end + "','yyyy-MM-dd hh24:mi:ss')");
        }
        return sb;
    }
}
